<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/webpage/include/taglib.jsp" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html style="overflow: auto;">
<head>
    <title>植百汇入库单</title>
    <script type="text/javascript" src="${ctxStatic}/plugin/layui2.0/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="${ctxStatic}/plugin/layui2.0/layui.js"></script>
    <link rel="stylesheet" href="${ctxStatic}/plugin/layui2.0/css/layui.css" media="all">
    <script src="${ctxStatic}/common/js/sku.js"></script>
    <script src="${ctxStatic}/common/js/jeeplus.js"></script>
    <%@ include file="/webpage/include/bootstraptable.jsp"%>
    <link rel="stylesheet" href="${ctxStatic}/common/css/app-blue.css" media="all"> 
    <link rel="stylesheet" href="${ctxStatic}/purchase/add_purchase.css" media="all"> 
    <script>
        var ctx = '${ctx}';
        var purchaseOrderId = '${purchaseOrderId}';
    </script>
    <script>
    	//查找仓库类型-原
        function findWarehouseType(warehouseType,arr){
            $.ajax({
                type : "post",
                url : ctx+"/sys/dict/findWarehouseTypeByTypeList?typeList="+arr, //此次url改为真正需要的url
                success : function(data) {
                    var optionstring = "<option value=''>"+"直接选择或搜索选择"+"</option>";
                    if(data!=null){
                        for(var i=0;i<data.length;i++){
                            optionstring += "<option value=\"" + data[i].value+ "\">" +data[i].label+ "</option>";
                        }
                    }
                    $("#"+warehouseType).html(optionstring);
                    layui.use('form', function () {
                        var form = layui.form;
                        form.render();
                    });
                }
            });
        }

        function findWarehouse(warehouseId,warehouseType) {
            $("#"+warehouseId).empty();
            var type=$("#"+warehouseType).val();
            $.ajax({
                type : "post",
                url : ctx+"/warehouse/warehouse/findByType?warehouseType="+type, //此次url改为真正需要的url
                success : function(data) {
                    var optionstring = "";
                    if(data!=null){
                        for(var i=0;i<data.length;i++){
                            optionstring += "<option value=\"" + data[i].id+ "\">" +data[i].warehouseName+ "</option>";
                        }
                    }
                    $("#"+warehouseId).html(optionstring);
                    layui.use('form', function () {
                        var form = layui.form;
                        form.render();
                    });
                }
            });
        };
    </script>
</head>
<body style="width:100%; height:100%; overflow: scroll; -webkit-overflow-scrolling: touch;">
	<div class="wrapper wrapper-content">				
			<div class="row">
				<div class="col-md-12">
					<div class="panel panel-primary">
						<div class="panel-heading">
							<h3 class="panel-title"> 
							   <span style="font-size:12px">质检入库  </span> 
								<a class="panelButton" href="${ctx}/warehouse/warehouseReceipt"><i class="ti-angle-left"></i> 返回</a>
							</h3>
						</div>
						<div class="panel-body">
						    <form class="layui-form" action="">
						        <!--入库单信息start-->
						        <div class="row">
						            <div class="col-xs-12 col-sm-6 col-md-3">
						                <label class="label-txt col-xs-4 col-sm-3">仓库类型：</label>
						                <div class="layui-input-inline col-xs-8 col-sm-9">
						                    <select id="warehouseType" lay-filter="warehouseType" name="warehouseType" lay-verify="required" lay-search="">
						                        <option value="">直接选择或搜索选择</option>
						                    </select>
						                </div>
						            </div>
						            <div class="col-xs-12 col-sm-6 col-md-3">
						                <label class="label-txt col-xs-4 col-sm-3" >仓库：</label>
						                <div class="layui-input-inline col-xs-8 col-sm-9">
						                  <select model="select"  id="warehouse" name="warehouse" lay-verify="required" lay-search="">
						                        <option value="">请选择</option>
						                    </select>
						                </div>
						            </div>
						        </div>
						        <!--入库单信息end-->
						    
						        <div class="row remarkRow">
							        <div class="col-xs-12 col-sm-9 col-md-9 ">
							        	 <label class='label-txt col-xs-4 col-sm-3 '>备注:</label>
							            <div class="layui-input-inline col-xs-8 col-sm-11">
							                <textarea id="remarks" name="remarks" placeholder="请输入内容" class="layui-textarea">${wr.remarks}</textarea>
							            </div>
							        </div>
						        </div>
						         <!-- 工具栏 -->
						         <div id="toolbar">
				                        <a  class="btn btn-primary" href="javascript:;"  onclick="sub()"><i
				                                class="glyphicon glyphicon-plus"></i> 选择SKU</a>
				                        <span  class="btn btn-info"  onclick="complete()">
				                            <i class="glyphicon glyphicon-link"></i> 确认质检入库
				                        </span>
				                        <span  class="btn btn-danger" onclick="reBack()">
				                            <i class="glyphicon glyphicon-save"></i>关闭
				                        </span>
				                </div>
				                <!-- 工具栏 -->
						        <style>
						                #purchaseOrder .self-adaption-wrap {
						                   overflow-x: scroll;
						               }
						               .self-adaption-wrap::-webkit-scrollbar {
						                   display: none;
						               }
						               #purchaseOrder .self-adaption-input{
						                   min-width: 200px;
						               }
						        </style>
						        <!--动态添加数据start-->
						        <div>
						        	<table id="purchaseOrder" data-toolbar="#toolbar"></table>
						        </div>
						        	
						        <!--动态添加数据end-->
						        <hr/>
						    </form>
						</div>
					</div>
				</div>
			</div>
		</div>
 </body>


<script>
    findWarehouseType("warehouseType",['1']);
</script>
<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->
<script>
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate;

        form.on('select(warehouseType)', function(data){
            findWarehouse('warehouse','warehouseType');
            form.render();
        });
    });
</script>
<script>

    function complete() {
        layer.confirm('确认入库后将会生成资源码,并且不可改?', {
                btn: ['确定', '取消']
            }, function (index, layero) {
                subForm();
            }
        );
    }

    function subForm() {
       // var purchaseOrder=new Object();
       /*  purchaseOrder.remarks=$("#remarks").val();//备注
        purchaseOrder.warehouseId=$("#warehouse").val();//仓库id */

        if(""==$("#warehouse").val()){
            layer.alert('仓库没有选择!', {
                icon: 2,
                title: "提示"
            });
            return ;
        }

        //采购明细单
        var items=$("#purchaseOrder").find("tbody tr");
        if(null==items || ""==items || items.length==0){
            layer.alert('请添加sku!', {
                icon: 2,
                title: "提示"
            });
            return;
        }

        var orderItems = new Array();
	    var orderItem;
	    for (var i = 0; i < items.length; i++) {
	        orderItem = new Object();
	        orderItem.skuId = $(items[i]).find("[name='sku']").val();
	        orderItem.price = $(items[i]).find("#price").val();
	        orderItem.num = $(items[i]).find("#num").val();

	        if (orderItem.skuId == "" || orderItem.price == "" || orderItem.num == "") {
	            layer.alert('有空数据请检查!', {
	                icon: 2,
	                title: "提示"
	            }); 
	           // jp.error("有空数据！");
	            return;
	        }
	        if(orderItem.num == "0"){
	        	layer.alert('采购数量不可以为0!', {
	                icon: 2,
	                title: "提示"
	            }); 
	            return;
	        }
	        //移动端数字处理
	        var reg = /^[1-9]\d*$/;
	        if(!reg.test(orderItem.num)){
	        	layer.alert('采购数量不可包含非数字', {
	                icon: 2,
	                title: "提示"
	            }); 
	            return;
	        }
	        var reg2 =/^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*)|0)$/;
	        if(!reg2.test(orderItem.price)){
	        	layer.alert('价格必须是数字', {
	                icon: 2,
	                title: "提示"
	            }); 
	            return;
	        }

	        orderItems.push(orderItem);
	    }
	    var fromData = new FormData();
        fromData.append("evidenceId",'${wr.evidenceId}');
        fromData.append("warehouseId",$("#warehouse").val());
        fromData.append("jsons",JSON.stringify(orderItems));
        fromData.append("remarks",$("#remarks").val());
        
        //提交数据
        $.ajax({
            url:"${ctx}/warehouse/warehouseReceipt/saveAndQc",
            type:"post",
            data:fromData,
            contentType: false, // 注意这里应设为false
            processData: false,
            beforeSend: function () {
                index = layer.load(1, {
                    shade: [0.5, '#fff'] //0.1透明度的白色背景
                });
            },
            complete: function () {
                layer.close(index);
            },
            success:function(data){
               if(data.message=="0"){
                    layer.alert('保存成功!',{icon:1,closeBtn:0},function(index){
                    	layer.close(index);
                    	reBack();
                    });
                }else if(data.message==1){
                    layer.alert(data.data, {
                        icon: 2,
                        title: "提示"
                    });

                } 
               
            },
            error:function(e){
                layer.alert('保存失败!', {
                    icon: 2,
                    title: "提示"
                });
            }
        });
    }

  /*   function reBack() {
        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
        parent.layer.close(index);//关闭页面
    } */
    function reBack(){
    	  window.location.href = "${ctx}/warehouse/warehouseReceipt";
    }
</script>
<script type="text/javascript">
    //弹窗选择sku
    function sub() {
        layer.open({
            type: 2,
            title: 'sku选择',
            maxmin: true, //开启最大化最小化按钮*!/
            area: ['96%', '90%'],
            content:ctx+"/sku/sku/pop",
            btn:['确定','取消'],
            yes : function(index,layero) {
            	//所有选中的记录
            	var rows=$(layero).find("iframe")[0].contentWindow.$("#skuTable").bootstrapTable('getSelections');
                if(null!=rows){
                	var count = $('#purchaseOrder').bootstrapTable('getData').length;
               	 var dataArr = $('#purchaseOrder').bootstrapTable('getData');
               	 var hasThead = $('#purchaseOrder>thead').length;
                	 if(hasThead>0){//有头部表示已经生成过表格
                		for(var i = 0; i < count; i++){
                            // 获取父级元素
                	            var eleParent = $('#purchaseOrder>tbody>tr:eq('+i+')');
                	            // 获取每个row对应field的值
                	            dataArr[i]['amount'] = eleParent.find("[name='num']").val();
                	            dataArr[i]['price'] = eleParent.find("[name='price']").val();
                	            console.log( dataArr[i]['amount'], dataArr[i]['amount']);
                	            // 更新option中的值
                	            $('#purchaseOrder').bootstrapTable('getOptions').data.splice(i, 1, dataArr[i]);
                        	}
                         	$.each(rows,function(idx,o){
                         	 	o.skuId=o.id;
                             	let skuName=o.productName+"：" + "["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_a'))}, o.categoryA, "-")+"]" +"—" +"["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_b'))},o.categoryB, "-")+"]" +"—" +"["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_c'))}, o.categoryC, "-")+"]";
                             	let res=checkSkuName(o.id);//校验是否重复
                             	if(!res){
                             	// 更新新建的row并添加到table中
                                  	 $('#purchaseOrder').bootstrapTable('insertRow',{
                                 		 index:count,
                                 		 row:{
                                 		 	skuId: o.skuId,
                                   	 		amount:o.amount,
                                   	 		skuName:skuName,
                                   	 		price:o.price+'canEdit'
                                 		 }
                                  });
                             	}
                         	});
                	 }
                }
            }
        });
    }
    //校验sku是否重复
    function checkSkuName(id) {
    	var k=0;
        var skus=$("#purchaseOrder").find("input[name='sku']");
        for(var i=0;i<skus.length;i++){
            if(id==$(skus[i]).val()){
                layer.alert('已存在相同的sku!', {
                    icon: 3,
                    title: "提示"
                });
                k=1;
            }
        }
        return k;
    }

    //添加
    function addItem(skuName,skuId) {
        var sku=$("#item").find("input[name='sku']");
        $(sku).attr("value",skuName);
        $(sku).attr("sku",skuId);
        var html="<div class=\"layui-form-item\" >"+$("#item").html()+"</div>";
        $("#purchaseOrder").append(html);
    }
    //删除
    function removeItem(obj,skuId) {
    	jp.confirm('确认要删除该SKU吗？', function(){
    		var $patr =$(obj).parents("tr");
    		//将该数据从数据源删除 
    		rowData =$('#purchaseOrder').bootstrapTable('getData');
    		for(var i=0;i<rowData.length;i++){
    			var o = rowData[i];
    			if(o.skuId==skuId){
    				rowData.splice(i,1);
    			}
    		}
    		if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){
   	    	 	$patr.next(".detail-view").remove();
    		}
   	    	$patr.remove();
		}) 
    }


    //采购数量
    function checkAmount(obj){
    	obj.value=obj.value.replace(/\D/g,'');
    }
    function checkPrice(obj){
    	obj.value=obj.value.replace(/[^\d\.]/g,'');
    }
    function initData(){
        //加载sku数据
        $('#purchaseOrder').bootstrapTable({
           url: "${ctx}/warehouse/warehouseReceipt/findPurchaseOrderItem?purchaseOrderId="+purchaseOrderId,
     	   contentType : "application/x-www-form-urlencoded",   //必须有
           striped: true,
      	   columns: [
      		   {
      	           title: '序号', //标题 可不加
      	           field:'scount',
      	           formatter: function (value, row, index) {
      	               return index + 1;
      	           },
      	       },
      		   {
      			   title:'SKUID',
      			   field:'skuId',
    	           formatter:function(value,row,index){
    	        	   return '<input class="noborder" value='+row.skuId+' name="sku" readOnly>';
    	           },
      		   },
      		   {
      		       field:'skuName',
    	           title: 'SKU',
    	       },
    	       {
    	           field: 'amount',
    	           title: '采购数量',
    	           class:'no-padding',
    	           formatter:function(value,row,index){
			         if(row.amount){
  		            	   return '<input class="form-input" value='+row.amount+' onkeyup="checkAmount(this)" name="num" id="num" autocomplete="off" placeholder="请输入采购数量">';
  		             }else{
  		           	   return '<input class="form-input" onkeyup="checkAmount(this)" name="num" id="num" autocomplete="off" placeholder="请输入采购数量">';
  		             }
			       }
    	        }, 
    	        {
    	           title: '采购单价',
    	           class:'no-padding',
    	           formatter:function(value,row,index){
    	        	   //若有canEdit 则
    	        	   if((row.price+"").indexOf('canEdit')!=-1){
    	        		   return '<input class="form-input"  placeholder="请输入采购单价" id="price" onkeyup="checkPrice(this)" onblur="checkPrice(this)" name="price" autocomplete="off"/>';
    	        	   }else{
    	        		   return '<input class="form-input"  value='+row.price+' placeholder="请输入采购单价" id="price" readOnly name="price" autocomplete="off"/>';
    	        	   }

    	           }
    	        }, {
    	               title: '操作',
    	               formatter:function(value,row,index){
    	        	     return "<span class='btn btn-danger table-btn ' onclick='removeItem(this,"+row.skuId+")'>删除</span>"
    	               }
    	     
    	          }
    	   ]
        });
    }
    $(function(){
    	initData();
    	if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端
	   		 $('#purchaseOrder').bootstrapTable("toggleView");
	   	}
    });
</script>
</html>